<template>
    <div class="calculator" >
      <n-input v-model:value="result" readonly placeholder="0" class="result-input" />
      <div class="buttons">
        <n-button
          v-for="button in buttons"
          :key="button"
          @click="handleClick(button)"
          class="button"
        >
          {{ button }}
        </n-button>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref } from 'vue';
  import { NInput, NButton } from 'naive-ui';
  
  const result = ref('0');
  const buttons = [
    '1', '2', '3', '+',
    '4', '5', '6', '-',
    '7', '8', '9', '*',
    'C', '0', '=', '/',
    '←', '^', '√', 
  ];
  
  const handleClick = (button: string) => {
    if (button === 'C') {
      result.value = '0';
    } else if (button === '=') {
      try {
        result.value = String(eval(result.value));
      } catch (error) {
        result.value = 'Error';
      }
    } else if (button === '←') {
      // 实现退格键功能
      result.value = result.value.slice(0, -1) || '0';
    } else if (button === '^') {
      // 实现次方功能
      result.value = result.value + '**';
    } else if (button === '√') {
      // 实现开方功能
      try {
        const lastNumber = result.value.match(/(\d+(\.\d+)?)$/)?.[0];
        if (lastNumber) {
          const sqrtValue = Math.sqrt(parseFloat(lastNumber));
          result.value = result.value.replace(lastNumber, sqrtValue.toString());
        }
      } catch (error) {
        result.value = 'Error';
      }
    } else {
      result.value = result.value === '0' ? button : result.value + button;
    }
  };
  </script>
  
  <style scoped>
  .calculator {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 320px; 
  }
  
  .result-input {
    width: 100%;
    margin-bottom: 10px;
    font-size:20px;
  }
  
  .buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr); /* 按钮自适应宽度 */
    gap: 8px;
    width: 100%;
  }
  
  .button {
    width: 100%;
    font-size:20px;
  }
  </style>